
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
import {encrypt} from "@/utils/passwordUtil";
import * as process from "process";
const db = cloud.database()
const _ = db.command
/**
 * 登录数据结构
 * @param ctx
 */
export default async function (ctx: FunctionContext) {
  let  body = ctx.body
  /**
   * {
   *   "username": "wuzuxian",
   *   "password": "wzxwsq1314",
   * }
   */
  //1.校验参数
  if (nw.util.isNull(body.username)){
    return fail("用户名为空")
  }
  if (nw.util.isNull(body.password)){
    return fail("密码为空")
  }
  //2.查询用户
  let user = await nw.db.findByWhereJson({
      dbName:"admin",
      whereJson:{
        deleted:_.eq(0),
        username:_.eq(body.username),
        password:_.eq(encrypt(body.password,process.env.SALT))
      }
  })

  if (nw.util.isNull(user)){
    return  fail("用户名或者密码不正确")
  }
  if (user.deleted==1){
    return fail("用户已经被禁用")
  }

  //3.组装token，并且保存数据库
  let payload = {
    admin:user._id,
    // 默认 token 有效期为 7 天，请务必提供此 `exp` 字段，详见 JWT 文档。
    exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7,
  }
  const access_token = cloud.getToken(payload);
  //4.更新登录时间
  let num =  await nw.db.update({
    dbName:"admin",
    whereJson:{
      _id: _.eq(user._id),
    },
    dataJson:{
      token:access_token,
      loginTime:new Date()
    }
  });
  if (num<=0){
    return fail("登录失败")
  }
  let result  = {
    token:access_token
  }
  return ok(result,"登录成功")
}
